<template>
  <div class="medical-record-handle">
    <el-card class="form-card" shadow="never" :body-style="{ padding: '24px' }">
      <el-form
        ref="medicalRecordFormRef"
        :model="formData"
        :rules="readonly ? {} : rules"
        label-width="120px"
        size="default"
        :disabled="readonly"
      >
        <!-- 基本信息卡片 -->
        <div class="section-title">基本信息</div>
        <div class="section-content">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="患者" prop="userId">
                <el-select
                  v-model="formData.userId"
                  placeholder="请选择患者"
                  style="width: 100%"
                  filterable
                  @change="handlePatientChange"
                >
                  <el-option
                    v-for="patient in patientList"
                    :key="patient.id"
                    :label="`${patient.name} (${patient.phone || '无电话'})`"
                    :value="patient.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="科室" prop="departmentId">
                <el-tree-select
                  v-model="formData.departmentId"
                  placeholder="请选择科室"
                  style="width: 100%"
                  :data="departmentTree"
                  node-key="id"
                  :props="{
                    label: 'name',
                    value: 'id',
                    children: 'children'
                  }"
                  check-strictly
                  clearable
                  filterable
                  @change="handleDepartmentChange"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="医生" prop="doctorId">
                <el-select
                  v-model="formData.doctorId"
                  placeholder="请选择医生"
                  style="width: 100%"
                  filterable
                  @change="handleDoctorChange"
                >
                  <el-option
                    v-for="doctor in filteredDoctorList"
                    :key="doctor.id"
                    :label="`${doctor.name} (${doctor.title || ''})`"
                    :value="doctor.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="就诊时间" prop="visitTime">
                <el-date-picker
                  v-model="formData.visitTime"
                  type="datetime"
                  placeholder="选择就诊时间"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 病情记录卡片 -->
        <div class="section-title">病情记录</div>
        <div class="section-content">
          <el-form-item label="主诉" prop="chiefComplaint">
            <el-input
              v-model="formData.chiefComplaint"
              type="textarea"
              :rows="3"
              placeholder="请描述患者主要症状和不适"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="现病史" prop="presentIllness">
            <el-input
              v-model="formData.presentIllness"
              type="textarea"
              :rows="3"
              placeholder="请详细描述患者现在的病情发展过程"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="既往史" prop="pastHistory">
            <el-input
              v-model="formData.pastHistory"
              type="textarea"
              :rows="2"
              placeholder="患者既往疾病史、药物过敏史等"
              maxlength="300"
              show-word-limit
            />
          </el-form-item>
        </div>

        <!-- 检查结果卡片 -->
        <div class="section-title">检查结果</div>
        <div class="section-content">
          <el-form-item label="体格检查" prop="physicalExamination">
            <el-input
              v-model="formData.physicalExamination"
              type="textarea"
              :rows="3"
              placeholder="体格检查结果记录"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="辅助检查" prop="auxiliaryExamination">
            <el-input
              v-model="formData.auxiliaryExamination"
              type="textarea"
              :rows="3"
              placeholder="化验、影像、心电图等检查结果"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>
        </div>

        <!-- 诊断与治疗卡片 -->
        <div class="section-title">诊断与治疗</div>
        <div class="section-content">
          <el-form-item label="诊断结果" prop="diagnosis">
            <el-input
              v-model="formData.diagnosis"
              type="textarea"
              :rows="2"
              placeholder="请填写诊断结果"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="治疗方案" prop="treatmentPlan">
            <el-input
              v-model="formData.treatmentPlan"
              type="textarea"
              :rows="3"
              placeholder="治疗方案和建议"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="医嘱" prop="medicalAdvice">
            <el-input
              v-model="formData.medicalAdvice"
              type="textarea"
              :rows="2"
              placeholder="医生的医嘱和注意事项"
              maxlength="300"
              show-word-limit
            />
          </el-form-item>
        </div>

        <!-- 住院信息卡片 -->
        <div class="section-title">住院信息</div>
        <div class="section-content">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="状态" prop="status">
                <el-select v-model="formData.status" placeholder="选择状态" style="width: 100%">
                  <el-option label="草稿" :value="0" />
                  <el-option label="已完成" :value="1" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="需要住院" prop="needHospitalization">
                <el-switch
                  v-model="formData.needHospitalization"
                  :active-value="true"
                  :inactive-value="false"
                  active-text="是"
                  inactive-text="否"
                  class="custom-switch"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <template v-if="formData.needHospitalization">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="住院状态" prop="hospitalizationStatus">
                  <el-tag :type="getHospitalizationStatusType(formData.hospitalizationStatus)" class="status-tag">
                    {{ getHospitalizationStatusText(formData.hospitalizationStatus) }}
                  </el-tag>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="预计住院天数" prop="estimatedDays">
                  <el-input-number
                    v-model="formData.estimatedDays"
                    :min="1"
                    :max="30"
                    :disabled="formData.hospitalizationStatus === 2"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="入院时间" prop="admissionTime">
                  <el-date-picker
                    v-model="formData.admissionTime"
                    type="datetime"
                    placeholder="入院时间"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    format="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="预计出院时间" prop="estimatedDischargeTime">
                  <el-date-picker
                    v-model="formData.estimatedDischargeTime"
                    type="datetime"
                    placeholder="预计出院时间"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    format="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </template>

          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="formData.remark"
              type="textarea"
              :rows="2"
              placeholder="其他备注信息"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </div>
      </el-form>

      <div class="dialog-footer" v-if="!readonly">
        <el-button @click="handleClose" class="cancel-btn">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading" class="submit-btn">
          {{ isEdit ? '更新' : '保存' }}
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { addMedicalRecord, updateMedicalRecord, getDepartmentTree } from '@/api/business'
import { getUserList, getDoctorList } from '@/api/admin'

const props = defineProps({
  medicalRecord: {
    type: Object,
    default: () => ({})
  },
  isEdit: {
    type: Boolean,
    default: false
  },
  readonly: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['success', 'close'])

// 表单引用
const medicalRecordFormRef = ref(null)
const submitLoading = ref(false)

// 列表数据
const patientList = ref([])
const doctorList = ref([])
const departmentTree = ref([])

// 表单数据
const formData = reactive({
  id: null,
  recordNo: '',
  registrationId: null,
  userId: null,
  userName: '',
  doctorId: null,
  doctorName: '',
  departmentId: null,
  departmentName: '',
  chiefComplaint: '',
  presentIllness: '',
  pastHistory: '',
  physicalExamination: '',
  auxiliaryExamination: '',
  diagnosis: '',
  treatmentPlan: '',
  medicalAdvice: '',
  visitTime: '',
  status: 0,
  remark: '',
  // 住院相关字段
  needHospitalization: false,
  wardId: null,
  bedNumber: null,
  estimatedDays: 7,
  hospitalizationStatus: 0,
  admissionTime: null,
  estimatedDischargeTime: null,
  actualDischargeTime: null
})

// 根据科室过滤医生列表
const filteredDoctorList = computed(() => {
  if (!formData.departmentId) {
    return doctorList.value
  }
  return doctorList.value
})

// 表单验证规则  
const rules = {
  userId: [
    { required: true, message: '请选择患者', trigger: 'change' }
  ],
  doctorId: [
    { required: true, message: '请选择医生', trigger: 'change' }
  ],
  departmentId: [
    { required: true, message: '请选择科室', trigger: 'change' }
  ],
  chiefComplaint: [
    { required: true, message: '请填写患者主诉', trigger: 'blur' }
  ],
  diagnosis: [
    { required: true, message: '请填写诊断结果', trigger: 'blur' }
  ],
  visitTime: [
    { required: true, message: '请选择就诊时间', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 获取患者列表
const getPatientList = async () => {
  try {
    const response = await getUserList({ role: 1, page: 1, size: 1000 }) // 患者角色为1
    if (response.code === 200 && response.data && response.data.list) {
      patientList.value = response.data.list
    }
  } catch (error) {
    console.error('获取患者列表失败:', error)
    ElMessage.error('获取患者列表失败')
  }
}

// 获取医生列表
const getDoctorListData = async () => {
  try {
    const response = await getDoctorList()
    console.log(response,'response')
    if (response.code === 200) {
      doctorList.value = response.data.list || []
    }
  } catch (error) {
    console.error('获取医生列表失败:', error)
    ElMessage.error('获取医生列表失败')
  }
}

// 获取科室树形数据
const getDepartmentTreeData = async () => {
  try {
    const response = await getDepartmentTree()
    if (response.code === 200) {
      departmentTree.value = response.data || []
    }
  } catch (error) {
    console.error('获取科室树形数据失败:', error)
    ElMessage.error('获取科室树形数据失败')
  }
}

// 处理患者选择变更
const handlePatientChange = (patientId) => {
  const patient = patientList.value.find(p => p.id === patientId)
  if (patient) {
    formData.userName = patient.name
  }
}

// 处理医生选择变更
const handleDoctorChange = (doctorId) => {
  const doctor = doctorList.value.find(d => d.id === doctorId)
  if (doctor) {
    formData.doctorName = doctor.name
    // 如果没有选择科室，自动选择医生所属科室
    if (!formData.departmentId) {
      formData.departmentId = doctor.departmentId
      handleDepartmentChange(doctor.departmentId)
    }
  }
}

// 处理科室选择变更
const handleDepartmentChange = (departmentId) => {
  const findDepartment = (list, id) => {
    for (const item of list) {
      if (item.id === id) {
        return item
      }
      if (item.children) {
        const found = findDepartment(item.children, id)
        if (found) {
          return found
        }
      }
    }
    return null
  }

  const department = findDepartment(departmentTree.value, departmentId)
  if (department) {
    formData.departmentName = department.name
  }
  // 如果当前选择的医生不属于新科室，清空医生选择
  if (formData.doctorId) {
    const currentDoctor = doctorList.value.find(d => d.id === formData.doctorId)
    if (currentDoctor && currentDoctor.departmentId !== departmentId) {
      formData.doctorId = null
      formData.doctorName = ''
    }
  }
}

// 初始化表单数据
const initFormData = () => {
  if (props.isEdit && props.medicalRecord) {
    Object.keys(formData).forEach(key => {
      if (props.medicalRecord[key] !== undefined) {
        formData[key] = props.medicalRecord[key]
      }
    })
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await medicalRecordFormRef.value.validate()
    
    submitLoading.value = true
    
    const data = { ...formData }
    
    if (props.isEdit) {
      await updateMedicalRecord(data)
      ElMessage.success('就诊记录更新成功')
    } else {
      await addMedicalRecord(data)
      ElMessage.success('就诊记录添加成功')
    }
    
    emit('success')
    handleClose()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitLoading.value = false
  }
}

// 关闭弹窗
const handleClose = () => {
  emit('close')
}

// 组件挂载时初始化
onMounted(async () => {
  await Promise.all([
    getPatientList(),
    getDoctorListData(), 
    getDepartmentTreeData()
  ])
  initFormData()
})

// 获取住院状态类型
const getHospitalizationStatusType = (status) => {
  const statusMap = {
    0: 'warning',  // 未住院
    1: 'success',  // 已入院
    2: 'info'      // 已出院
  }
  return statusMap[status] || 'info'
}

// 获取住院状态文本
const getHospitalizationStatusText = (status) => {
  const statusMap = {
    0: '未住院',
    1: '已入院',
    2: '已出院'
  }
  return statusMap[status] || '未知'
}

// 监听预计住院天数变化
watch(() => formData.estimatedDays, (newVal) => {
  if (newVal && formData.needHospitalization) {
    // 更新预计出院时间
    if (formData.admissionTime) {
      // 将字符串转换为日期对象进行计算
      const admissionDate = new Date(formData.admissionTime.replace(' ', 'T'))
      const dischargeDate = new Date(admissionDate.getTime() + newVal * 24 * 60 * 60 * 1000)
      // 格式化为后端需要的格式
      formData.estimatedDischargeTime = dischargeDate.toISOString().slice(0, 19).replace('T', ' ')
    }
  }
})

// 监听需要住院状态变化
watch(() => formData.needHospitalization, (newVal) => {
  if (!newVal) {
    // 清空住院相关字段
    formData.wardId = null
    formData.bedNumber = null
    formData.estimatedDays = 7
    formData.hospitalizationStatus = 0
    formData.admissionTime = null
    formData.estimatedDischargeTime = null
    formData.actualDischargeTime = null
  }
})
</script>

<style scoped>
.medical-record-handle {
  padding: 16px;
  background-color: #f5f7fa;
  min-height: 100%;
}

.form-card {
  background-color: #fff;
  border-radius: 8px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2f3d;
  margin: 24px 0 16px;
  padding-left: 12px;
  border-left: 4px solid #409eff;
}

.section-title:first-child {
  margin-top: 0;
}

.section-content {
  padding: 0 12px;
  margin-bottom: 24px;
}

.el-form {
  max-height: calc(100vh - 200px);
  overflow-y: auto;
  padding-right: 12px;
}

.el-form::-webkit-scrollbar {
  width: 6px;
}

.el-form::-webkit-scrollbar-thumb {
  background-color: #dcdfe6;
  border-radius: 3px;
}

.el-form::-webkit-scrollbar-track {
  background-color: #f5f7fa;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-textarea__inner) {
  resize: none;
  border-radius: 4px;
  font-family: inherit;
}

:deep(.el-input__wrapper),
:deep(.el-textarea__inner) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
  transition: all 0.3s;
}

:deep(.el-input__wrapper:hover),
:deep(.el-textarea__inner:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

:deep(.el-input__wrapper:focus-within),
:deep(.el-textarea__inner:focus) {
  box-shadow: 0 0 0 1px #409eff inset;
}

.custom-switch {
  --el-switch-on-color: #409eff;
}

.status-tag {
  font-size: 14px;
  padding: 6px 12px;
}

.dialog-footer {
  text-align: right;
  padding-top: 24px;
  border-top: 1px solid #ebeef5;
  margin-top: 24px;
}

.cancel-btn {
  margin-right: 12px;
}

.submit-btn {
  min-width: 100px;
}

:deep(.el-row) {
  margin-bottom: 0 !important;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-card__body) {
  padding: 24px !important;
}
</style> 